package com.piesat.feaedit.feaedit.controller;


import com.northpool.resources.datatable.SpatialInfo;
import com.northpool.spatial.Constants;
import com.piesat.feaedit.feaedit.base.exception.BusinessException;
import com.piesat.feaedit.feaedit.base.response.BaseResponse;
import com.piesat.feaedit.feaedit.bean.FeatureBean;
import com.piesat.feaedit.feaedit.bean.request.DeleteRequest;
import com.piesat.feaedit.feaedit.bean.request.QueryFeatureRequest;
import com.piesat.feaedit.feaedit.bean.request.ServiceStatus;
import com.piesat.feaedit.feaedit.bean.request.UpdateFeatureRequest;
import com.piesat.feaedit.feaedit.config.ProjectConfig;
import com.piesat.feaedit.feaedit.service.IFeatureService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class FeatureController {
   final ProjectConfig projectConfig;

    final IFeatureService service;


    public FeatureController(ProjectConfig projectConfig, IFeatureService service) {
        this.projectConfig = projectConfig;
        this.service = service;
    }

    @PostMapping("/upload")
    public BaseResponse handleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName) {
        if (file.isEmpty()) {
            return BaseResponse.failure("文件为空");
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 文件保存路径
            String filePath = Paths.get(projectConfig.getUploadDir(), fileName).toString();

            // 将文件写入磁盘
            Path target = Paths.get(filePath);
            File zipFile = new File(filePath);
            if(zipFile.exists()) {
                zipFile.delete();
            }
            Files.copy(file.getInputStream(), target);

            service.dataEntry(zipFile, tableName);

            return BaseResponse.success("文件已成功上传到: " + filePath);
        } catch (IOException e) {
            throw new BusinessException("上传失败: " + e.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/query")
    public BaseResponse findFeature(@RequestBody QueryFeatureRequest request) {
        FeatureBean feature = service.findFeature(request.getTableName(), request.getLng(), request.getLat());
        return BaseResponse.success("OK", feature);
    }

    @PostMapping("/update")
    public BaseResponse updateFeature(@RequestBody UpdateFeatureRequest request) {
        service.updateFeature(request);
        return BaseResponse.success("OK");
    }

    @PostMapping("/delete")
    public BaseResponse deleteFeature(@RequestBody DeleteRequest request) {
        service.deleteFeature(request.getTableName(), request.getFeatureId());
        return BaseResponse.success("OK");
    }

    @PostMapping("/deleteAll")
    public BaseResponse deleteAllFeature(@RequestBody DeleteRequest request) {
        service.deleteAllData(request.getTableName());
        return BaseResponse.success("OK");
    }

    @GetMapping("/taskInfo")
    public BaseResponse taskInfo(String taskId, String type) {
        Object status = service.queryTask(taskId, type);
        if(status == null) {
            throw new BusinessException("未找到任务信息");
        }else {
            return BaseResponse.success("OK", status);
        }
    }

    @GetMapping("/publish")
    public BaseResponse publish(String tableName) throws IOException {
        // GEO_TYPE
        ServiceStatus status = service.publishServer(tableName,"#000000", "1", "1", "#000000" , "1");
        if(status == null) {
            throw new BusinessException("未找到任务信息");
        }else {
            return BaseResponse.success("OK", status);
        }
    }
    @GetMapping("/export/{tableName}")
    public BaseResponse export(@PathVariable String tableName) throws UnsupportedEncodingException {
        this.service.exportShp(tableName);
        return BaseResponse.success("OK");
    }

    @GetMapping("/download/{tableName}")
    public ResponseEntity<FileSystemResource> downloadFile(@PathVariable String tableName) throws IOException {
        // 创建文件资源
        FileSystemResource fileResource = this.service.download(tableName);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + tableName + ".zip");

        // 返回文件下载响应
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(fileResource.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(fileResource);
    }
}
